"""
设备管理API视图
"""
from django.db.models import Q, Count
from django.utils import timezone
from rest_framework import viewsets, status, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import filters

from .models import Device, DeviceBrand, DeviceType, PlatformCredential, DeviceCommand
from .serializers import (
    DeviceListSerializer, DeviceDetailSerializer, DeviceBrandSerializer,
    DeviceTypeSerializer, PlatformCredentialSerializer, DeviceCommandSerializer,
    DeviceControlSerializer, DeviceStatusSerializer, DeviceStatisticsSerializer
)


class StandardResultsSetPagination(PageNumberPagination):
    """标准分页配置"""
    page_size = 20
    page_size_query_param = 'page_size'
    max_page_size = 100


class DeviceViewSet(viewsets.ModelViewSet):
    """设备管理ViewSet"""
    queryset = Device.objects.select_related('brand', 'device_type', 'owner', 'platform_credential')
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['connection_status', 'brand', 'device_type', 'room']
    search_fields = ['name', 'device_id', 'room']
    ordering_fields = ['name', 'created_at', 'updated_at', 'connection_status']
    ordering = ['-created_at']
    
    def get_serializer_class(self):
        """根据动作选择序列化器"""
        if self.action == 'list':
            return DeviceListSerializer
        return DeviceDetailSerializer
    
    def get_queryset(self):
        """获取当前用户的设备"""
        return self.queryset.filter(owner=self.request.user)
    
    def perform_create(self, serializer):
        """创建设备时设置所有者"""
        serializer.save(owner=self.request.user)
    
    @action(detail=True, methods=['post'])
    def control(self, request, pk=None):
        """控制设备"""
        device = self.get_object()
        serializer = DeviceControlSerializer(data=request.data)
        
        if serializer.is_valid():
            command = serializer.validated_data['command_id']
            parameters = serializer.validated_data.get('parameters', {})
            
            # 验证命令是否属于该设备类型
            if command.device_type != device.device_type:
                return Response({
                    'success': False,
                    'message': '该命令不适用于当前设备类型'
                }, status=status.HTTP_400_BAD_REQUEST)
            
            try:
                # 这里应该调用实际的设备控制逻辑
                # 目前返回模拟结果
                result = self._execute_device_command(device, command, parameters)
                
                return Response({
                    'success': True,
                    'message': f'命令 "{command.name}" 执行成功',
                    'result': result
                })
            except Exception as e:
                return Response({
                    'success': False,
                    'message': f'命令执行失败: {str(e)}'
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
    
    @action(detail=True, methods=['get'])
    def status(self, request, pk=None):
        """获取设备状态"""
        device = self.get_object()
        
        try:
            # 这里应该调用实际的设备状态检查逻辑
            # 目前返回模拟结果
            status_info = self._check_device_status(device)
            
            serializer = DeviceStatusSerializer(status_info)
            return Response({
                'success': True,
                'data': serializer.data
            })
        except Exception as e:
            return Response({
                'success': False,
                'message': f'状态检查失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    @action(detail=False, methods=['get'])
    def statistics(self, request):
        """获取设备统计信息"""
        user_devices = self.get_queryset()
        
        # 基本统计
        total_devices = user_devices.count()
        online_devices = user_devices.filter(status='online').count()
        offline_devices = user_devices.filter(status='offline').count()
        unknown_devices = user_devices.filter(status='unknown').count()
        
        # 按类型统计
        devices_by_type = dict(
            user_devices.values('device_type__name')
            .annotate(count=Count('id'))
            .values_list('device_type__name', 'count')
        )
        
        # 按品牌统计
        devices_by_brand = dict(
            user_devices.values('brand__name')
            .annotate(count=Count('id'))
            .values_list('brand__name', 'count')
        )
        
        # 最近活动（模拟数据）
        recent_activities = [
            {
                'device_name': device.name,
                'action': '状态更新',
                'timestamp': device.updated_at,
                'status': device.get_status_display()
            }
            for device in user_devices.order_by('-updated_at')[:10]
        ]
        
        statistics_data = {
            'total_devices': total_devices,
            'online_devices': online_devices,
            'offline_devices': offline_devices,
            'unknown_devices': unknown_devices,
            'devices_by_type': devices_by_type,
            'devices_by_brand': devices_by_brand,
            'recent_activities': recent_activities
        }
        
        serializer = DeviceStatisticsSerializer(statistics_data)
        return Response({
            'success': True,
            'data': serializer.data
        })
    
    def _execute_device_command(self, device, command, parameters):
        """执行设备命令（模拟实现）"""
        # 这里应该根据设备的平台凭证和命令配置
        # 调用相应的设备控制API
        # 目前返回模拟结果
        
        import time
        import random
        
        # 模拟执行时间
        time.sleep(0.1)
        
        # 模拟执行结果
        if random.random() > 0.1:  # 90% 成功率
            return {
                'command': command.name,
                'parameters': parameters,
                'execution_time': timezone.now(),
                'response': '命令执行成功'
            }
        else:
            raise Exception("设备响应超时")
    
    def _check_device_status(self, device):
        """检查设备状态（模拟实现）"""
        # 这里应该根据设备的网络地址或平台API
        # 检查设备的实际状态
        # 目前返回模拟结果
        
        import random
        
        # 模拟状态检查
        statuses = ['online', 'offline', 'unknown']
        current_status = random.choice(statuses)
        
        return {
            'status': current_status,
            'last_seen': timezone.now(),
            'response_time': random.uniform(10, 500),  # 10-500ms
        }


class DeviceBrandViewSet(viewsets.ModelViewSet):
    """设备品牌管理ViewSet"""
    queryset = DeviceBrand.objects.all()
    serializer_class = DeviceBrandSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [filters.SearchFilter, filters.OrderingFilter]
    search_fields = ['name']
    ordering_fields = ['name', 'created_at']
    ordering = ['name']


class DeviceTypeViewSet(viewsets.ModelViewSet):
    """设备类型管理ViewSet"""
    queryset = DeviceType.objects.prefetch_related('commands')
    serializer_class = DeviceTypeSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['category']
    search_fields = ['name', 'category']
    ordering_fields = ['name', 'category', 'created_at']
    ordering = ['category', 'name']


class PlatformCredentialViewSet(viewsets.ModelViewSet):
    """平台凭证管理ViewSet"""
    queryset = PlatformCredential.objects.all()
    serializer_class = PlatformCredentialSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['platform_name', 'is_active']
    search_fields = ['platform_name', 'username']
    ordering_fields = ['platform_name', 'created_at']
    ordering = ['platform_name']
    
    def get_queryset(self):
        """获取当前用户的平台凭证"""
        return self.queryset.filter(owner=self.request.user)
    
    def perform_create(self, serializer):
        """创建平台凭证时设置所有者"""
        serializer.save(owner=self.request.user)
    
    @action(detail=True, methods=['post'])
    def test_connection(self, request, pk=None):
        """测试平台连接"""
        credential = self.get_object()
        
        try:
            # 这里应该调用实际的平台连接测试逻辑
            # 目前返回模拟结果
            result = self._test_platform_connection(credential)
            
            return Response({
                'success': True,
                'message': '连接测试成功',
                'result': result
            })
        except Exception as e:
            return Response({
                'success': False,
                'message': f'连接测试失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def _test_platform_connection(self, credential):
        """测试平台连接（模拟实现）"""
        import time
        import random
        
        # 模拟连接测试
        time.sleep(0.5)
        
        if random.random() > 0.2:  # 80% 成功率
            return {
                'platform': credential.platform_name,
                'status': 'connected',
                'response_time': random.uniform(100, 1000),
                'test_time': timezone.now()
            }
        else:
            raise Exception("连接超时或认证失败")


class DeviceCommandViewSet(viewsets.ModelViewSet):
    """设备命令管理ViewSet"""
    queryset = DeviceCommand.objects.select_related('device_type')
    serializer_class = DeviceCommandSerializer
    permission_classes = [permissions.IsAuthenticated]
    pagination_class = StandardResultsSetPagination
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['device_type']
    search_fields = ['command']
    ordering_fields = ['command', 'created_at']
    ordering = ['created_at']